import md5 from "js-md5";
// uni.request请求封装
import config from "@/common/js/configTemp.js";

// const apiUrl = config.BASE_URL+'v2/';
console.log(process.env.NODE_ENV)

const sortParams = function(myJson) {
	var sortedObjKeys = Object.keys(myJson).sort();
	var str = "";
	for (var index in sortedObjKeys) {
		str += sortedObjKeys[index] + "=" + myJson[sortedObjKeys[index]] + "&";
	}
	if (str) {
		str += config.OPEN_KEY;
	}
	return str;
}

let apiUrl = config.BASE_URL + 'app/api/';
if (process.env.NODE_ENV == "development") {
	apiUrl = '/app/api/';
}

function get(url = "", params = {}) {
	let reqUrl = apiUrl + url;
	return new Promise((resolve, reject) => {
		console.log('====get===', reqUrl)
		uni.request({
			url: reqUrl,
			data: params,
			header: {
				"Content-Type": "application/json",
			},
			method: "GET",
			timeout: 1000000,
			success(rep) {
				console.log("http->response:", rep.data);
				if (rep.statusCode == 200) {
					resolve(rep.data);
				} else {
					reject(rep.errMsg);
				}
			},
			fail(err) {
				console.warn("http error:", err);
				reject(err);
			},
		});
	});
}

function post(
	path = "",
	params = {},
	optional = {
		responseType: 0,
		contentType: "application/x-www-form-urlencoded",
		timeout: 1000000,
	}
) {
	let reqUrl = apiUrl + path;
	let log = "【POST】URL:" + reqUrl;
	// if (getApp().globalData.userInfo.userId) {
	// 	datas.token = getApp().globalData.userInfo.token
	// }
	
	let datas = params
	let timestamp = Date.parse(new Date());
	timestamp = timestamp / 1000
	datas.identifier = timestamp
	datas.version = config.VERSION
	datas.channelId = config.CHANNELID
	// if (getApp().globalData.userInfo.userId) {
	// 	datas.token = getApp().globalData.userInfo.token
	// }
	
	datas.checksum = md5(sortParams(datas))
	console.log("http->request:", reqUrl, params);
	return new Promise((resolve, reject) => {
		uni.request({
			url:reqUrl,
			data: datas,
			header: {
				"Content-Type": optional.contentType || "application/x-www-form-urlencoded",
			},
			method: "POST",
			timeout: optional.timeout || 8000,
			success(rep) {
				let res = rep.data;
				console.log("http->response:", res);
				if (res) {
					resolve(res);
				} else {
					reject(res);
				}
			},
			fail(err) {
				console.warn("http error:", err);
				reject(err);
			},
		});
	});
}

export {
	get,
	post
};